package com.supor.aiot.food.ui.food;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONObject;
import com.android.baseconfig.common.views.CustomTitleBar;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.food.R;
import com.supor.aiot.food.adapter.ImgPagerAdapter;
import com.supor.aiot.food.adapter.SharedRecipe1Adapter;
import com.supor.aiot.food.api.SearchFoodImpl;
import com.supor.aiot.food.bean.RecipeHotBean;
import com.supor.aiot.food.bean.RecipeTopicBean;
import com.supor.aiot.food.bean.TopicDetailBean;

import java.util.ArrayList;
import java.util.List;


public class SharedRecipeTwoFragment extends Fragment {

    TextView tvSharedTitle;
    TextView tvSharedContent;
    ViewPager vpRecipes;
    TextView tvSharedDevice;
    TextView tvrecipeName;
    TextView tvrecipeDesc;
    NestedScrollView scrollView;
    TextView tvTotalSize;
    View noneMore;
    ImageView ivPlayVedio;

    private ImgPagerAdapter pagerAdapter;
    private ViewGroup group;
    private ImageView imageView;
    //定义一个ImageVIew数组，来存放生成的小园点
    private ImageView[] imageViews;
    private int originPage = 1;
    private String dataID;

    private List<RecipeHotBean> mlist = new ArrayList<>();
    private TopicDetailBean recipeTopicBean;
    private SharedRecipeActivity sharedRecipeActivity;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shared_recipe_type2, container, false);
        initView(view);
        initData();
        initPointer();
        return view;
    }

    private void initData() {
        sharedRecipeActivity = (SharedRecipeActivity) getActivity();
        dataID=sharedRecipeActivity.getDataID();
        recipeTopicBean = sharedRecipeActivity.getTopicDetail();
        if (recipeTopicBean != null && !TextUtils.isEmpty(recipeTopicBean.getCuisineTitel())){
            tvSharedTitle.setText(recipeTopicBean.getCuisineTitel());
        }

        if (recipeTopicBean != null && !TextUtils.isEmpty(recipeTopicBean.getCuisineDescribe()))
            tvSharedContent.setText(recipeTopicBean.getCuisineDescribe());

        pagerAdapter=new ImgPagerAdapter(mlist);
        pagerAdapter.setImgClickListener(position -> {
            AppAgent.startRecipePage(mlist.get(position).getRecipeId(), mlist.get(position).getModelId());
        });
        vpRecipes.setAdapter(pagerAdapter);
        getTopicRecipe(dataID);
    }


    @SuppressLint("AutoDispose")
    private void getTopicRecipe(String dataId){
        SearchFoodImpl.getInstance().getTopicRecipe(dataId,originPage,100).subscribe(result->{
            if (result.isSuccess()) {
                if (originPage == 1) mlist.clear();
                if (mlist.size() < result.total) {
                    mlist.addAll(result.data.rows);
                }
                if (mlist.size()>0){
                    tvTotalSize.setVisibility(View.VISIBLE);
                    tvSharedDevice.setVisibility(View.VISIBLE);
                    RecipeHotBean hotBean = mlist.get(0);
                    if (!TextUtils.isEmpty(hotBean.getCrmModelName()))tvSharedDevice.setText(hotBean.getCrmModelName());
                    if (!TextUtils.isEmpty(hotBean.getRecipeName()))tvrecipeName.setText(hotBean.getRecipeName());
                    if (!TextUtils.isEmpty(hotBean.getRecipeContent()))tvrecipeDesc.setText(hotBean.getRecipeContent());
                    tvTotalSize.setText("1/"+mlist.size());
                    if (!TextUtils.isEmpty(hotBean.getRecipeType()) && hotBean.getRecipeType().equals("VIDEO")) {
                        ivPlayVedio.setVisibility(View.VISIBLE);
                    } else {
                        ivPlayVedio.setVisibility(View.GONE);
                    }
                    noneMore.setVisibility(View.VISIBLE);
                }else {
                    tvTotalSize.setVisibility(View.GONE);
                    tvSharedDevice.setVisibility(View.GONE);
                    noneMore.setVisibility(View.GONE);
                }
                pagerAdapter.notifyDataSetChanged();
            } else {
                Log.e("SharedRecipeOneFragment", "Recipe error");
            }
        },throwable -> {
            Log.e("SharedRecipeOneFragment", "Recipe查询失败: " + throwable.getMessage());
        });
    }

    private void initView(View view) {
        tvSharedTitle = view.findViewById(R.id.tv_shared_title);
        tvSharedContent = view.findViewById(R.id.tv_shared_content);
        vpRecipes = view.findViewById(R.id.vp_shared_img);
        tvSharedDevice = view.findViewById(R.id.tv_shared_tag);
        tvrecipeName = view.findViewById(R.id.tv_shared_img_tag);
        group = view.findViewById(R.id.ll_shared_dot);
        tvrecipeDesc = view.findViewById(R.id.tv_recipe_desc);
        tvTotalSize = view.findViewById(R.id.tv_total);
        noneMore = view.findViewById(R.id.none_more);
        ivPlayVedio = view.findViewById(R.id.iv_play_vedio);

        //设置监听
        vpRecipes.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //页面滑动是执行
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            //页面滑动完成后执行
            @Override
            public void onPageSelected(int position) {
                //判断当前是在那个page，就把对应下标的ImageView原点设置为选中状态的图片
                for (int i = 0; i < imageViews.length; i++) {
                    imageViews[position%mlist.size()].setBackgroundResource(R.drawable.dot_white_bg);
                    if (position%mlist.size() != i) {
                        imageViews[i].setBackgroundResource(R.drawable.dot_gray_bg);
                    }
                }
                RecipeHotBean hotBean = mlist.get(position%mlist.size());
                if (!TextUtils.isEmpty(hotBean.getCrmModelName()))tvSharedDevice.setText(hotBean.getCrmModelName());
                if (!TextUtils.isEmpty(hotBean.getRecipeName()))tvrecipeName.setText(hotBean.getRecipeName());
                if (!TextUtils.isEmpty(hotBean.getRecipeContent()))tvrecipeDesc.setText(hotBean.getRecipeContent());
                tvTotalSize.setText((position%mlist.size()+1)+"/"+mlist.size());
                if (!TextUtils.isEmpty(hotBean.getRecipeType()) && hotBean.getRecipeType().equals("VIDEO")) {
                    ivPlayVedio.setVisibility(View.VISIBLE);
                } else {
                    ivPlayVedio.setVisibility(View.GONE);
                }
            }

            //监听页面的状态，0--静止 1--滑动  2--滑动完成
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        scrollView = view.findViewById(R.id.nest_scroll);
        scrollView.setOnScrollChangeListener((View.OnScrollChangeListener) (view1, i, i1, i2, i3) -> {
            if (i1>150){
                sharedRecipeActivity.showTitle();
            }else {
                sharedRecipeActivity.hideTitle();
            }
        });
    }

    //根据页面的个数动态添加圆点指示器
    private void initPointer() {
        //有多少个界面就new多长的数组
        imageViews = new ImageView[mlist.size()];
        for (int i = 0; i < imageViews.length; i++) {
            //new新的ImageView控件
            imageView = new ImageView(getActivity());
            //设置控件的宽高
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int)getActivity().getResources().getDimension(R.dimen.dp_6),(int) getActivity().getResources().getDimension(R.dimen.dp_6));
            layoutParams.setMargins((int) getActivity().getResources().getDimension(R.dimen.dp_3),0,(int) getActivity().getResources().getDimension(R.dimen.dp_3),0);
            imageView.setLayoutParams(layoutParams);

            imageViews[i] = imageView;
            //初始化第一个page页面的图片的原点为选中状态
            if (i == 0) {
                //表示当前图片
                imageViews[i].setBackgroundResource(R.drawable.dot_white_bg);
                /**
                 * 在java代码中动态生成ImageView的时候
                 * 要设置其BackgroundResource属性才有效
                 * 设置ImageResource属性无效
                 */
            } else {
                imageViews[i].setBackgroundResource(R.drawable.dot_gray_bg);
            }
            //把new出来的ImageView控件添加到线性布局中
            group.addView(imageViews[i]);
        }

    }
}
